/**
 * 
 */
package edu.arizona.bio5.onto.decomposition.persistent.file;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLEntity;

import edu.arizona.bio5.onto.decomposition.Label;
import edu.arizona.bio5.onto.decomposition.MSSLabel;
import edu.arizona.bio5.onto.decomposition.persistent.LabelLoader;
import edu.arizona.bio5.onto.util.OntologyUtils;

/**
 * @author Pavel Klinov
 *
 */
public class SeedSigsLabelLoader implements LabelLoader<String> {

	private OWLDataFactory m_factory = null;
	private String m_input = null;
	
	public SeedSigsLabelLoader(OWLDataFactory factory) {
		
		m_factory = factory;
	}
	
	/* 
	 */
	@Override
	public Label load() {
		//Checking prefix
		boolean isComplete = m_input.startsWith(DiskADConstants.COMPLETE_LABEL_PREFIX);
		//Loading stuff, TODO error handling
		Pattern sigsPattern = Pattern.compile("\\[[^\\[\\]]+\\]");
		Matcher sigsMatcher = sigsPattern.matcher(m_input);
		//String[] sigs = labelString.split("\\[[^\\[\\]]+\\]");
		Collection<Set<OWLEntity>> seedSigs = new ArrayList<Set<OWLEntity>>();
		
		while (sigsMatcher.find()) {
			
			String sig = sigsMatcher.group();
			
			sig = sig.substring(1, sig.length() - 1);//Getting rid of '[' and ']'
			
			String[] termStrings = sig.split(",");
			Set<OWLEntity> termSig = new HashSet<OWLEntity>(termStrings.length);
			
			for (String termString : termStrings) {
				
				termSig.add(OntologyUtils.termFromString(m_factory, termString));
			}
			
			seedSigs.add(termSig);
		}
		
		return new MSSLabel(seedSigs, isComplete);
	}

	@Override
	public void setInput(String input) {
		m_input = input;
	}
}